package com.leo.persistence.config;

import com.leo.persistence.pojo.Configuration;
import com.leo.persistence.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * mapper.xml解析
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) {
        try {

            Document document = new SAXReader().read(in);
            Element rootElement = document.getRootElement();

            String namespace = rootElement.attributeValue("namespace");

            /**
             * 添加MappedStatement到config里的map集合，同时添加执行类型
             */
            wrapper(namespace, SqlCommandType.SELECT, rootElement.selectNodes("//select"));
            wrapper(namespace, SqlCommandType.DELETE, rootElement.selectNodes("//delete"));
            wrapper(namespace, SqlCommandType.UPDATE, rootElement.selectNodes("//update"));
            wrapper(namespace, SqlCommandType.INSERT, rootElement.selectNodes("//insert"));


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void wrapper(String namespace, SqlCommandType sqlCommandType, List<Element> list) {
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlCommandType(sqlCommandType);

            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
